<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElBreadcrumb, ElBreadcrumbItem } from 'element-plus';
import { getClassById } from '@/api/manager.js';

const route = useRoute();
const router = useRouter();
const classData = ref(null);

// 将 classId 改为 computed，确保响应路由 params 变化
const classId = computed(() => route.params.id);

// 规范化路径，移除末尾斜杠和查询参数
const normalizePath = (path) => {
  return path.split('?')[0].replace(/\/$/, '');
};

// 获取班级详情
async function fetchClassDetails() {
  const id = classId.value;
  if (!id) {
    console.error('无效的班级 ID:', id);
    ElMessage.error('无效的班级 ID');
    return;
  }
  try {
    console.log('尝试获取班级详情，classId:', id);
    const res = await getClassById(id);
    console.log('班级详情响应:', res);
    if (res.code === 200) {
      classData.value = res.detail;
    } else {
      ElMessage.error(`获取班级详情失败: ${res.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取班级详情失败:', error);
    ElMessage.error('获取班级详情失败，请稍后重试');
  }
}

// 监听路由参数变化，重新加载班级详情
watch(() => classId.value, (newId) => {
  if (newId) {
    fetchClassDetails();
  }
}, { immediate: true });

// 面包屑数据，使用 classId.value 确保响应变化
const breadcrumbItems = computed(() => {
  const id = classId.value;
  const currentPath = normalizePath(route.path);
  console.log('当前路由路径:', currentPath);
  const items = [
    {
      title: '排课表',
      path: `/educational/classManagement/classDetails/${id}/schedule`,
    },
    {
      title: '已上课表',
      path: `/educational/classManagement/classDetails/${id}/completed`,
    },
    {
      title: '签到记录',
      path: `/educational/classManagement/classDetails/${id}/attendance`,
    },
    {
      title: '班级学员',
      path: `/educational/classManagement/classDetails/${id}/students`,
    },
  ];
  console.log('面包屑路径:', items.map(item => item.path));
  return items;
});
</script>

<template>
  <div class="min-h-screen bg-white flex flex-col">
    <!-- 上半部分：班级详情 -->
    <div class="w-full bg-white shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <h1 class="text-2xl font-bold text-gray-800 mb-4">班级详情</h1>
        <div v-if="classData" class="bg-white rounded-lg shadow-md p-6 transition-all duration-300 hover:shadow-lg">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="班级名称" label-class-name="font-semibold text-gray-600">
              {{ classData.className }}
            </el-descriptions-item>
            <el-descriptions-item label="课程名称" label-class-name="font-semibold text-gray-600">
              {{ classData.courseName }}
            </el-descriptions-item>
            <el-descriptions-item label="讲师" label-class-name="font-semibold text-gray-600">
              {{ classData.teacher }}
            </el-descriptions-item>
            <el-descriptions-item label="开班时间" label-class-name="font-semibold text-gray-600">
              {{ classData.startTime }}
            </el-descriptions-item>
            <el-descriptions-item label="结班时间" label-class-name="font-semibold text-gray-600">
              {{ classData.endTime }}
            </el-descriptions-item>
            <el-descriptions-item label="所属校区" label-class-name="font-semibold text-gray-600">
              {{ classData.belongTo }}
            </el-descriptions-item>
            <el-descriptions-item label="班级状态" label-class-name="font-semibold text-gray-600">
              <span :class="classData.classStatus === 1 ? 'text-green-600' : 'text-red-600'">
                {{ classData.classStatus === 1 ? '正常' : '停用' }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="课程属性" label-class-name="font-semibold text-gray-600">
              {{ classData.courseProperty }}
            </el-descriptions-item>
            <el-descriptions-item label="计划课时数" label-class-name="font-semibold text-gray-600">
              {{ classData.planCourseCount }}
            </el-descriptions-item>
            <el-descriptions-item label="剩余课时数" label-class-name="font-semibold text-gray-600">
              {{ classData.remainCourseCount }}
            </el-descriptions-item>
            <el-descriptions-item label="班级容量" label-class-name="font-semibold text-gray-600">
              {{ classData.volume }}
            </el-descriptions-item>
            <el-descriptions-item label="默认教室" label-class-name="font-semibold text-gray-600">
              {{ classData.defaultClassroom }}
            </el-descriptions-item>
            <el-descriptions-item label="课堂时间" label-class-name="font-semibold text-gray-600">
              {{ classData.classTime }}
            </el-descriptions-item>
            <el-descriptions-item label="是否完成" label-class-name="font-semibold text-gray-600">
              <span :class="classData.isCompleted === 1 ? 'text-green-600' : 'text-red-600'">
                {{ classData.isCompleted === 1 ? '是' : '否' }}
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-else class="text-center py-10">
          <el-icon :size="30" class="animate-spin text-blue-500"><Loading /></el-icon>
          <p class="text-gray-500 mt-2">加载中...</p>
        </div>
      </div>
    </div>
    <!-- 下半部分：面包屑 + router-view -->
    <div class="w-full bg-white">
      <div class="container mx-auto px-4 py-6">
        <div class="bg-white rounded-lg shadow-md p-6">
          <el-breadcrumb separator="/" class="mb-4">
            <el-breadcrumb-item
                v-for="item in breadcrumbItems"
                :key="item.path"
                :to="{ path: item.path }"
                :class="{ 'is-active': normalizePath($route.path) === normalizePath(item.path) }"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <router-view :key="$route.fullPath"></router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import 'https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css';

.el-descriptions :deep(.el-descriptions__cell) {
  padding: 12px;
}

.el-descriptions :deep(.el-descriptions__label) {
  background-color: #f8fafc;
  width: 150px;
}

.el-descriptions :deep(.el-descriptions__content) {
  background-color: #ffffff;
}

/* 未激活面包屑项：黑色，加粗 */
.el-breadcrumb :deep(.el-breadcrumb__inner) {
  color: #000000;
  font-weight: bold;
}

/* 悬停时：黑色，加粗，保持一致 */
.el-breadcrumb :deep(.el-breadcrumb__inner:hover) {
  color: #000000;
  font-weight: bold;
}

/* 激活面包屑项：蓝色，加粗 */
.el-breadcrumb :deep(.el-breadcrumb__item.is-active .el-breadcrumb__inner) {
  color: #409eff;
  font-weight: bold;
}
</style>